package com.tencent.qcloud.qiaoqiao.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.design.widget.TextInputLayout;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.tencent.qcloud.qiaoqiao.R;
import com.tencent.qcloud.qiaoqiao.common.utils.TCUtils;
import com.tencent.qcloud.qiaoqiao.ui.activity.MainUIActivity;
import com.tencent.qcloud.qiaoqiao.ui.bean.UserInfoBean;
import com.tencent.qcloud.qiaoqiao.ui.net.FastJsonTools;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpRequest;
import com.tencent.qcloud.qiaoqiao.ui.net.HttpResultListener;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ActivityUtils;
import com.tencent.qcloud.qiaoqiao.ui.tools.utilCode.ToastUtils;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;

import java.util.Map;

import okhttp3.FormBody;
import okhttp3.RequestBody;

public class TCLoginActivity extends Activity {

    private static final String TAG = "TCLoginActivity";
    //共用控件
    private ProgressBar progressBar;
    private EditText etPassword;
    private AutoCompleteTextView etLogin;
    private Button btnLogin;
    private TextInputLayout tilLogin, tilPassword;
    private TextView tvRegister;
    private Context mContext;
    private int loginType = 0;//默认为0 1为微信登录
    private RelativeLayout loginLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mContext = this;
        loginLayout =  (RelativeLayout) findViewById(R.id.login_rl_root);

        etLogin = (AutoCompleteTextView) findViewById(R.id.et_login);

        etPassword = (EditText) findViewById(R.id.et_password);

        tvRegister = (TextView) findViewById(R.id.btn_register);

        btnLogin = (Button) findViewById(R.id.btn_login);

        progressBar = (ProgressBar) findViewById(R.id.progressbar);

        tilLogin = (TextInputLayout) findViewById(R.id.til_login);

        tilPassword = (TextInputLayout) findViewById(R.id.til_password);

        loginType = getIntent().getIntExtra("type",0);
        if (loginType==1){
            wxLogin();
            loginLayout.setVisibility(View.GONE);
        } else {
            //检测是否存在缓存
            checkLogin();
        }
        userNameLoginViewInit();
    }

    /**
     * 用户名密码登录界面init
     */
    public void userNameLoginViewInit() {
        etLogin.setInputType(EditorInfo.TYPE_CLASS_TEXT);

        etLogin.setText("");
        etLogin.setError(null, null);

        etPassword.setText("");
        etPassword.setError(null, null);

        tilLogin.setHint(getString(R.string.activity_login_username));

        tilPassword.setHint(getString(R.string.activity_login_password));

        tvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //注册界面 phoneView 与 normalView跳转逻辑一致
                Intent intent = new Intent();
                intent.setClass(getApplicationContext(), TCRegisterActivity.class);
                startActivity(intent);
            }
        });
        //微信登录
        findViewById(R.id.btn_wx_login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                wxLogin();
            }
        });

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //调用normal登录逻辑
                showOnLoading(true);
                attemptNormalLogin(etLogin.getText().toString(), etPassword.getText().toString());
            }
        });
    }

    private void wxLogin(){
        showOnLoading(true);
        UMShareAPI mShareAPI= UMShareAPI.get(mContext);
        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
        mShareAPI.doOauthVerify((Activity) mContext, platform, umAuthListener);
    }

    /**
     * trigger loading模式
     *
     * @param active
     */
    private void showOnLoading(boolean active) {
        if (active) {
            progressBar.setVisibility(View.VISIBLE);
            btnLogin.setVisibility(View.INVISIBLE);
            etLogin.setEnabled(false);
            etPassword.setEnabled(false);
            tvRegister.setClickable(false);
        } else {
            progressBar.setVisibility(View.GONE);
            btnLogin.setVisibility(View.VISIBLE);
            etLogin.setEnabled(true);
            etPassword.setEnabled(true);
            tvRegister.setClickable(true);
            tvRegister.setTextColor(getResources().getColor(R.color.colorTransparentGray));
        }

    }

    private void showToast(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void showOnLoadingInUIThread(final boolean active) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showOnLoading(active);
            }
        });
    }

    private void showLoginError(String errorString) {
        etLogin.setError(errorString);
        showOnLoading(false);
    }

    private void showPasswordError(String errorString) {
        etPassword.setError(errorString);
        showOnLoading(false);
    }

    /**
     * 登录成功后被调用，跳转至TCMainActivity
     */
    private void jumpToHomeActivity() {
        showToast("登录成功");
        ActivityUtils.finishAllActivities();
        ActivityUtils.startActivity(MainUIActivity.class);
    }

    private void login(final String username, String password) {
        final TCUserMgr tcLoginMgr = TCUserMgr.getInstance();
        tcLoginMgr.login(username, password, new TCUserMgr.Callback() {
            @Override
            public void onSuccess(JSONObject data) {
                jumpToHomeActivity();
            }

            @Override
            public void onFailure(int code, final String msg) {
                showToast(msg);
                showOnLoadingInUIThread(false);
            }
        });
    }

    private void checkLogin() {
        if (TCUtils.isNetworkAvailable(this)) {
            //返回true表示存在本地缓存，进行登录操作，显示loadingFragment
            if (TCUserMgr.getInstance().hasUser()) {
                showOnLoadingInUIThread(true);
                TCUserMgr.getInstance().autoLogin(new TCUserMgr.Callback() {
                    @Override
                    public void onSuccess(JSONObject data) {
                        jumpToHomeActivity();
                    }

                    @Override
                    public void onFailure(int code, final String msg) {
//                        showToast("自动登录失败");
                        showOnLoadingInUIThread(false);
                    }
                });
            }
        }
    }

    /**
     * 用户名密码登录
     *
     * @param username 用户名
     * @param password 密码
     */
    public void attemptNormalLogin(String username, String password) {
        if (TCUtils.isUsernameVaild(username)) {
            if (TCUtils.isPasswordValid(password)) {
                if (TCUtils.isNetworkAvailable(this)) {
                    login(username, password);
                } else {
                    Toast.makeText(getApplicationContext(), "当前无网络连接", Toast.LENGTH_SHORT).show();
                }
            } else {
                showPasswordError("密码长度应为8-16位");
            }
        } else {
            showLoginError("用户名不符合规范");
        }
    }

    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA share_media) {
//            4 = {HashMap$HashMapEntry@5977} "openid" -> "o0dDs0ZF1yi7QDHg8_3TqpnpAwck"
//            1 = {HashMap$HashMapEntry@5974} "access_token" -> "14_l6JxwHKoKPnpXtjUEXUAZR1j9nh-EBd2XqNE5RdHP4T6c-_Bl3IMPvCRSc9jPtvEux9Ll_8vxjZZ_5-bDQDRO_z3MK-bB4UQ3klk_Z5q3t0"
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
           // Toast.makeText(mContext, "Authorize succeed", Toast.LENGTH_SHORT).show();
            if (data!=null){
                wxUserInfo(data.get("access_token"),data.get("openid"));
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
            Toast.makeText(mContext, "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
            Toast.makeText(mContext, "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    private void wxUserInfo(String access_token, String openId){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openId+"&lang=zh_CN";
        HttpRequest.requestGet(url, new HttpResultListener() {
            @Override
            public void onSuccess(String data) {
                if (data==null){
                    ToastUtils.showShort("数据获取错误");
                    return;
                }
                com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data);
                RequestBody formBody = new FormBody.Builder()
                        .add("uid", jsonObject.getString("openid"))
                        .add("name",  jsonObject.getString("nickname"))
                        .add("gander", jsonObject.getString("sex"))
                        .add("iconurl",  jsonObject.getString("headimgurl"))
                        .add("province",  jsonObject.getString("province"))
                        .add("city", jsonObject.getString("city")).build();
                HttpRequest.requestPost("wechatlogin", formBody, new HttpResultListener() {
                    @Override
                    public void onSuccess(String data) {
                        showLoginError("数据错误");
                        if (TextUtils.isEmpty(data)){
                            ToastUtils.showShort("数据错误");
                            return;
                        }
                        UserInfoBean infoBean = FastJsonTools.getPerson(data, UserInfoBean.class);
//                        SharedPreferences settings = mContext.getSharedPreferences("TCUserInfo", Context.MODE_PRIVATE);
//                        SharedPreferences.Editor editor = settings.edit();
//                        editor.putString("userid", infoBean.getUserid());
//                        editor.putString("userpwd",infoBean.getPassword());
//                        editor.putString("mToken", infoBean.getNickname());
//                        editor.commit();
                        TCUserMgr.getInstance().setUserId(infoBean.getUserid());
                        login(infoBean.getUserid(),infoBean.getPassword());
//                        jumpToHomeActivity();
                    }

                    @Override
                    public void onFailure(String data) {
                        ToastUtils.showShort("失败");
                    }
                });
            }

            @Override
            public void onFailure(String data) {
                ToastUtils.showShort("失败");
            }
        });
    }

}
